var express = require('express');
var fs = require('fs');
var mongoose = require('mongoose');
var path = require('path');
var queryString = require('querystring');
var url = require('url');

var budget_server = require('./lib/budget_server');
var user_server = require('./lib/user_server');
var view_server = new (require('./lib/view_server')).ViewServer();

var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'this is a bad secret'}));

Array.prototype.last = function(){
	return this[this.length-1];
}	
Array.prototype.contains = function(item){
	return this.indexOf(item) > -1;
}

function ServeStatic(url, response){
	var path = '.'+url;
	console.log('Serving static: '+path);
	fs.exists(path, 
		(function(path){
			return function(exists){
				if(exists){
					response.sendfile(path);
				}
				else{
					response.status(404).send('Not found');
				}
			};
		})(path)
	);
}

// Request Demultiplexer
app.all('*', function(request, response, next){
	var request_class = request.url.split('/')[1];
	
	switch(request_class){
		case 'static':
			ServeStatic(request.url, response);
			break;
		
		case 'view':
			view_server.Serve(request, response);
			break;
			
		case 'action': // handles requests for database updates and for data retreival 
			HandleAction(request, response);
			break;
			
		default:
			response.redirect('/static/login.html');
	}
});

function HandleAction(request, response){
	var action = request.url.split('/').last().split('?')[0];
	
	console.log('Action request: '+action);
	
	var handler = budget_server[action] || user_server[action];
    if(handler == undefined){
        // 404
    }
    else{
        handler(request, response);
    }
}


app.listen(8000, function(){
	if(process.argv[2] == 'local'){
		mongoose.connect('mongodb://localhost/budget');
		console.log('Using local database');
	}
	else{
		mongoose.connect('mongodb://nodejitsu_natehs:7hdib04tfvfva6ibdrgrkk00ue@ds059887.mongolab.com:59887/nodejitsu_natehs_nodejitsudb7818864206');
		console.log('Using remote database');
	}
	var db = mongoose.connection;
	db.on('error', console.error.bind(console, 'Database connection error:'));
	db.once('open', function(){ console.log('Database connection opened'); });
});